﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NVelocity.App;
using NVelocity.Context;
using Commons.Collections;
using NVelocity.Runtime;
using NVelocity;
using NVelocity.App.Tools;
using System.IO;

namespace CnGine.CodeGenerator.Help
{
    public class VelocityHelper
    {
        private VelocityEngine velocity = null;
        private IContext context = null;
        //模板目录存放的位置
        private string tempDirectory = Help.CommHelper.GetAssemblyPath() + @"\Templates";

        public VelocityHelper()
        {
            //创建VelocityEngine实例对象
            velocity = new VelocityEngine();
            //使用设置初始化VelocityEngine
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, tempDirectory);
            props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
            props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");

            velocity.Init(props);
            //为模板变量赋值
            context = new VelocityContext();
            context.Put("formatter", new VelocityFormatter(context));
        }

        /// <summary>
        /// 给模板变量赋值
        /// </summary>
        /// <param name="key">模板变量</param>
        /// <param name="value">模板变量值</param>
        public void Set(string key, object value)
        {
            if (context == null)
            {
                context = new VelocityContext();
            }
            context.Put(key, value);
        }
        /// <summary>
        /// 根据模板引擎生成代码内容
        /// </summary>
        /// <param name="tempName"></param>
        /// <returns></returns>
        public bool GeneratorCode(string tempName, string savePath)
        {
            try
            {
                //从文件中读取模板
                Template template = velocity.GetTemplate(tempName, "UTF-8");
                //合并模板
                StringWriter writer = new StringWriter();
                template.Merge(context, writer);

                using (StreamWriter sw = new StreamWriter(savePath, false, Encoding.UTF8, 200))
                {
                    sw.Write(writer);
                    sw.Flush();
                    sw.Close();
                }
                writer.Flush();
                writer.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }


    }
}
